<?php
namespace App\Http\Controllers;
use pay\WxpayAPI\WeEncryption as WeEncryption;
use pay\phpqrcode\QRcode as QRcode;

class WeipayController extends Controller {

	public function __construct()
	{
		$this->appid        = config('wei.ent_appid');//公众账号ID
		$this->mchid        = config('wei.ent_mchid');//商户号
		$this->key      = config('wei.app_key');
		$this->sslcert_path = config('wei.ent_sslcert_path');//退款证书路径（正式）
		$this->sslkey_path  = config('wei.ent_sslkey_path');//退款证书密钥(正式)
		$this->encpt        = new WeEncryption($this->key,$this->sslcert_path,$this->sslkey_path); //实例化签名类
	}


	/**
	 * 微信请求支付接口
	 * https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
	 */
	public function weiPayQuery(){
		$data = [
			'body' => "test",
			'attach' => "test",
			'out_trade_no' => "sdkphp123456789".date("YmdHis"),
			'total_fee' => "100",
			'goods_tag' => "test",
			'notify_url' => "https://www.weiweidagong.com/development.php/ent/Alipay/notify_verify",
			'trade_type' => "NATIVE",
			'product_id' => "123456789",
			'spbill_create_ip' => '127.0.0.1',
			'appid' => $this->appid,
			'mch_id' => $this->mchid,
			'nonce_str' => self::getNonceStr(),
		];

		$result = $this->encpt->GetPayUrl($data);
		$QRcode = new QRcode;
		if(substr($result["code_url"], 0, 6) == "weixin"){
			//生成二维码图片
			$src = $QRcode::png($result["code_url"]);
			return view('welcome',['src'=> $src]);
		}

	}

	/**
	 * 微信申请退款接口
	 * https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_4
	 */
	public function refund($out_trade_no = 'sdkphp12345678920180813024003',$out_refund_no = '4200000159201808135134916129',$total_fee = 1,$refund_fee = 1,$transaction_id = ''){
		$data =
			[
				'out_trade_no'  => $out_trade_no,
				'out_refund_no' => $out_refund_no,
				'total_fee' 	=> $total_fee,
				'refund_fee' 	=> $refund_fee,
				'appid'  		=> $this->appid,
				'mch_id' 		=> $this->mchid,
				'nonce_str' => self::getNonceStr(),
			];
		$result = $this->encpt->refund($data);
		dd($result);
	}

	/**
	 *  查询退款
	 * 	https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_5
	 */
	public function refundQuery($out_trade_no = 'sdkphp12345678920180813024003',$transaction_id = ''){
		$data =
			[
				'out_trade_no'  => $out_trade_no,
				'appid'  		=> $this->appid,
				'mch_id' 		=> $this->mchid,
				'nonce_str' => self::getNonceStr(),
			];
		$result = $this->encpt->refundQuery($data);
		dd($result);
	}

	

	


	/**
	 * 获取随机数；
	 * @return String 返回生成的随机数；
	 */
	public function getNonceStr() {
		$code = "";
		for ($i=0; $i > 10; $i++) {
			$code .= mt_rand(10000);
		}
		$nonceStrTemp = md5($code);
		$nonce_str = mb_substr($nonceStrTemp, 5,37);
		return $nonce_str;
	}

}
